const mongoose = require('mongoose')
const restify = require('restify')
const crypto = require('crypto')
const secret = crypto.randomBytes(32).toString('hex')
const app = restify.createServer()
app.use(restify.plugins.bodyParser())

//CORS处理
app.pre((req, res, next) => {


	res.header('Access-Control-Allow-Origin', req.header('origin'));
	res.header('Access-Control-Allow-Headers', req.header('Access-Control-Request-Headers'));
	res.header('Access-Control-Allow-Credentials', 'true');
	res.header("Access-Control-Expose-Headers","Content-Disposition")
	 if (req.method === 'OPTIONS') // if is preflight(OPTIONS) then response status 204(NO CONTENT)
	return res.send(204);
	next()
})


//系统配置
const config = require('./config')
//无需签权的接口
require('./exclude')(app, secret, config.excludelist);
//引入redis
require('./redis/rediscon')
//api列表
require('./api')(app, secret)


//监听服务
app.listen(3006, () => {
	mongoose.connect('mongodb://localhost/' + config.dbBase);
	const db = mongoose.connection;
	db.on('open', async () => {
		console.log('数据库连接成功');
	});
	db.on('error', (error) => {
		console.log(error);
	})
})